<template>
    <div>
        <el-form :inline="true" :model="condition" class="search-form" label-width="120px" @keyup.enter.native="enterSearch">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="箱号">
                        <el-input v-model="condition['search_LIKE_containerId']"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="箱型">
                        <auto-search-entrust v-model="condition['search_LIKE_containerType']"
                                             :name="condition['search_LIKE_containerType']"></auto-search-entrust>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="尺寸">
                        <auto-search-size v-model="condition['search_LIKE_containerSize']"
                                          :name="condition['search_LIKE_containerSize']"></auto-search-size>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业港口">
                        <select-port :name="portName" v-model="choicePortCode" :isMultiple = "true"></select-port>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="创建时间">
                        <date-slot :startDate.sync="condition.search_GTE_createDateTime"
                                   :endDate.sync="condition.search_LTE_createDateTime"></date-slot>
                        <!-- <el-date-picker v-model="condition['search_GTE_createDateTime']"
                                        :picker-options="startPickerOptions" type="date" placeholder="起始日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker> -->
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="船代">
                        <auto-search-custom @selectName="v=>condition['search_LIKE_shipAgentName']=v"
                                            :isShipAgent="true"></auto-search-custom>
                    </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                    <el-form-item label="创建时间止">
                        <el-date-picker v-model="condition['search_LTE_createDateTime']" @change="handleChangeEnd"
                                        :picker-options="endPickerOptions" type="date" placeholder="结束日期"
                                        format="yyyy-MM-dd" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                    </el-form-item>
                </el-col> -->
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="作业类型">
                        <el-select v-model="condition['search_EQ_planType']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictTsJobStatus" :key="key" :label="val" :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="进出口">
                        <el-select v-model="condition['search_EQ_imOrEx']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictImportAndExportType" :key="key" :label="val"
                                       :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="是否结算">
                        <el-select v-model="condition['search_EQ_isAccount']" placeholder="请选择" clearable>
                            <el-option v-for="[key, val] in _dictTrueOrFalse" :key="key" :label="val"
                                       :value="key">
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-button type="primary" class="ml-120" @click="loadData">查 询</el-button>
                    <!--<el-button @click="handleAdd">新 增</el-button>-->
                    <el-button @click="handleSettle">结 算</el-button>
                    <el-button @click="handleExport">导出Excel</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-row type="flex" justify="end" class="mt-10 ">
            <el-col :span="4">
                <el-tag size="medium">
                    {{ selectTitle }}
                </el-tag>
            </el-col>
            <el-col :span="20" style="display: flex;justify-content: space-between">
                <!--<title-point color="#30C8CA">-->
                    <!--<div slot="content">-->
                        <!--未作业箱 :-->
                        <!--<span style="font-size: 16px">{{ noJobteu }} TEU</span>-->
                    <!--</div>-->
                <!--</title-point>-->
                <title-point color="#449DFF">
                    <div slot="content">
                        已作业箱 :
                        <span style="font-size: 16px">{{ jobTeu }} TEU</span></div>
                </title-point>
                <title-point color="#30C8CA">
                    <div slot="content">
                        总箱量 :
                        <span style="font-size: 16px">{{ totleNum }}</span>
                    </div>
                </title-point>
                <title-point color="#449DFF">
                    <div slot="content">
                        结算箱量 :
                        <span style="font-size: 16px">{{ settleJob }}</span></div>
                </title-point>
                <title-point color="#50B155">
                    <div slot="content">
                        未结算箱量 :
                        <span style="font-size: 16px">{{ nosettleJob }}</span></div>
                </title-point>
                <title-point color="#30C8CA">
                    <div slot="content">
                        进口箱量 :
                        <span style="font-size: 16px">{{ importJob }} </span>
                    </div>
                </title-point>
                <title-point color="#449DFF">
                    <div slot="content">
                        出口箱量 :
                        <span style="font-size: 16px">{{ exportJob }}</span></div>
                </title-point>
            </el-col>
        </el-row>
        <el-table :data="list" border stripe max-height="500" class="mt-10" @selection-change="handleSelectionChange">
            <el-table-column fixed="left" type="selection" :selectable="selectable" prop="id"
                             width="55"></el-table-column>
            <el-table-column prop="containerId" label="箱号" fixed="left"  min-width="120">
                <template slot-scope="scope">
                    <el-button size="small" type="text" @click="handleDetail(scope.row)">
                        {{ scope.row.containerId }}
                    </el-button>
                </template>
            </el-table-column>
            <!--<el-table-column type="index" label="序号"  width="55"></el-table-column>-->
            <el-table-column prop="portName" label="作业港口"  min-width="110"></el-table-column>
            <el-table-column prop="containerSize" label="尺寸"  min-width="75"></el-table-column>
            <el-table-column prop="containerType" label="箱型"  min-width="75"></el-table-column>
            <el-table-column prop="tradeType" label="内外贸"  min-width="100">
                <template slot-scope="scope">
                    {{ scope.row.tradeType | _filterTradeType }}
                </template>
            </el-table-column>
            <el-table-column prop="imOrEx" label="进出口"  min-width="100">
                <template slot-scope="scope">
                    {{ scope.row.imOrEx | _filterImportExport }}
                </template>
            </el-table-column>
            <el-table-column prop="sealNo" label="铅封号" min-width="100"></el-table-column>
            <el-table-column prop="finishTime" label="完成日期"  min-width="110">
                <template slot-scope="scope">
                    {{ scope.row.finishTime | filterDate }}
                </template>
            </el-table-column>
            <el-table-column prop="" label="施封日期"  min-width="110">
                <template slot-scope="scope">
                    {{scope.row.tallyTime | filterDate}}
                </template>
            </el-table-column>
            <el-table-column prop="planType" label="作业类型"  min-width="120">
                <template slot-scope="scope">
                    {{ scope.row.planType | _filterTsJobStatus }}
                </template>
            </el-table-column>
            <el-table-column prop="isAccount" label="是否结算"  min-width="120">
                <template slot-scope="scope">
                    {{ scope.row.isAccount | _filterTrueOrFalse }}
                </template>
            </el-table-column>
            <el-table-column prop="remark" label="描述" show-overflow-tooltip min-width="120"></el-table-column>
            <el-table-column prop="shipAgentName" label="船代" min-width="120"></el-table-column>
            <el-table-column prop="accountUnit" label="结算单位" min-width="120"></el-table-column>
            <el-table-column prop="finishUser" label="完成人" min-width="120"></el-table-column>
            <el-table-column prop="finishTime" label="完成时间"  min-width="160"></el-table-column>
            <el-table-column prop="createDateTime" label="创建时间"  min-width="160"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作"  width="140">
                <template slot-scope="scope">
                    <el-button size="small" v-if="power('TALLY_WORK_SPECIALLIST:UPD')" type="text"
                               @click="handleEdit(scope.row)">编辑
                    </el-button>
                    <el-dropdown style="margin-left:10px">
                            <span class="el-dropdown-link">
                                <el-button size="small" type="text">更多
                                    <i class="el-icon-arrow-down el-icon--right"></i>
                                </el-button>
                            </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>
                                <el-button type="text" v-if="power('TALLY_WORK_SPECIALLIST:DEL')"
                                           :disabled="scope.row.isAccount" class="danger" size="small"
                                           @click="handleRemove(scope.row.planId)">删除
                                </el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button size="small" :disabled="!scope.row.isAccount" type="text"
                                           @click="handleCancel(scope.row)">撤销结算
                                </el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>

                </template>
            </el-table-column>
        </el-table>
        <el-row class="bottom mt-10" type="flex" justify="space-between" v-show="total>0">
            <div class="oper">

            </div>
            <el-pagination class="page" @size-change="size=>pageInfo.iDisplayLength=size"
                           layout="total, sizes, prev, pager, next, jumper"
                           :current-page.sync="pageInfo.pageStart" :page-sizes="pageInfo.pageArr"
                           :page-size="pageInfo.iDisplayLength" :total="total">
            </el-pagination>
        </el-row>
        <el-dialog title="现结撤销结算" :visible.sync="cancelForm" width="400px">
            <el-form :model="cForm" label-width="100px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="箱号：">
                            {{ cForm.containerId }}
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="退款金额：">
                            <el-input-number style="width: 188px" :controls="false"
                                             v-model="cForm.accountFee"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="撤销备注：" prop="remark">
                            <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="cForm.remark"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelForm = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="$store.getters.loadingBtn">确 定</el-button>
            </span>
        </el-dialog>
        <special-form v-if="dialogForm" ref="specialForm" @load="loadData"></special-form>
        <special-detail-form v-if="dialogForm" ref="specialDetailForm"></special-detail-form>
        <special-settle-form v-if="specialSettleForm" ref="specialSettleForm" @load="loadData"></special-settle-form>
    </div>
</template>

<script>
    import autoSearchEntrust from '@/components/autocomplete/autoSearchEntrust'
    import autoSearchSize from '@/components/autocomplete/autoSearchSize'
    import autoSearchCustom from '@/components/autocomplete/autoSearchCustom'
    import autoSearchPortStation from '@/components/autocomplete/autoSearchPortStation'
    import { getPlanList, getPlanId, deletePlanList } from '@/api/planList/planList.js'
    import { cancelSpecial, getSpecialNum } from "@/api/shipPlan/shipPlan";
    import specialForm from './specialForm'
    import specialDetailForm from './specialDetailForm'
    import titlePoint from '../common/title-point'
    import selectPort from '@/components/select/selectPort'
    import dateSlot from '@/components/date/dateSlot'
    import specialSettleForm from './specialSettleForm'
    import { newExportExcel } from "@/utils/newExport";
    import { tradeType, trueOrFalse, importAndExportType, tsJobStatus, portCode } from "../../../assets/dict";

    export default {
        name: "特殊理箱",
        components: {
            autoSearchPortStation,
            specialForm,
            specialDetailForm,
            autoSearchEntrust,
            autoSearchSize,
            autoSearchCustom,
            titlePoint,
            selectPort,
            specialSettleForm,
            dateSlot
        },
        data() {
            return {
                condition: {},
                cForm: {},
                list: [],
                select: [],
                total: 0,
                pageInfo: this.$defalutPage(),
                listLoading: false,
                dialogForm: false,
                cancelForm: false,
                specialSettleForm: false,
                totleNum: 0,
                settlement: 0,
                noSettlement: 0,
                inNum: 0,
                outNum: 0,
                created: true,
                noJobteu: 0,
                jobTeu: 0,
                portName:'',
                settleJob: 0,
                nosettleJob: 0,
                importJob: 0,
                exportJob: 0,
                choicePortCode : []
            }
        },
        mounted() {
            const condition = JSON.parse(sessionStorage.getItem('ctIndex'))
            this.condition = { ...condition }
            const SHIP_DATE = sessionStorage.getItem('SHIP_DATE')
            this.portName = this.condition.search_EQ_portCode
            this.choicePortCode = this.condition.search_EQ_portCode
            this.condition.search_EQ_portCode = ""
            if (SHIP_DATE) {
                // this.condition['search_GTE_createDateTime'] = SHIP_DATE + ' 00:00:00'
                // this.condition['search_LTE_createDateTime'] = SHIP_DATE + ' 23:59:59'
                this.$set(this.condition, 'search_GTE_createDateTime', SHIP_DATE + ' 00:00:00')
                this.$set(this.condition, 'search_LTE_createDateTime', SHIP_DATE + ' 23:59:59')
            }

            this.loadData()
        },
        activated() {
            if (!this.created) {
                this.loadData()
            }
        },
        methods: {
            loadData() {
                this.listLoading = true
                if(typeof this.choicePortCode  === 'string'){
                    this.condition.search_IN_portCode = this.choicePortCode
                } else {
                    this.condition.search_IN_portCode = this.arrayToString(this.choicePortCode)
                }
                // this.condition.search_IN_portCode = this.arrayToString(this.choicePortCode)
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = this.pageInfo.iDisplayLength
                params.sortType = '-createDateTime'
                params.search_EQ_type = 'TS'
                getPlanList(params).then(res => {
                    this.created = false
                    const data = res.data
                    this.noJobteu = data.noJobteu
                    this.jobTeu = data.jobTeu
                    this.total = data.data.iTotalRecords
                    this.listLoading = false
                    this.list = data.data.aaData
                    this.totleNum = data.totleNum
                    this.settleJob = data.settleJob
                    this.nosettleJob = data.nosettleJob
                    this.importJob = data.importJob
                    this.exportJob = data.exportJob
                    this.settlement = 0
                    this.noSettlement = 0
                    this.inNum = 0
                    this.outNum = 0
                    this.list.forEach(f => {
                        if (f.imOrEx === 'I') {
                            this.inNum = this.inNum + 1
                        }
                        if (f.imOrEx === 'O') {
                            this.outNum = this.outNum + 1
                        }
                        if (f.isAccount === true) {
                            this.settlement = this.settlement + 1
                        }
                        if (f.isAccount === false) {
                            this.noSettlement = this.noSettlement + 1
                        }
                    })
                })
            },
            arrayToString:function(arr){
                let value = ""
                if (arr != null && arr != "" && arr.length > 0){
                    arr.forEach((column, index) => {
                        value = value + "," + column
                    })
                    value = value.substring(1)
                }
                return value
            },
            enterSearch() {
                this.loadData()
            },
            handleEdit(item) {
                getPlanId(item.planId).then(res => {
                    this.dialogForm = true
                    this.$nextTick(() => {
                        this.$refs.specialForm.dialogForm = true
                        this.$refs.specialForm.isEdit = true
                        let form = JSON.parse(JSON.stringify(res.data))
                        delete form.records
                        this.$refs.specialForm.form = form
                        this.$refs.specialForm.form['attachments'] = form['attachments'] || []
                        this.$refs.specialForm.table = res.data.records
                    })
                })
            },
            handleAdd() {
                this.dialogForm = true
                this.$nextTick(() => {
                    this.$refs.specialForm.dialogForm = true
                    this.$refs.specialForm.isEdit = false
                })
            },
            handleSettle() {
                if (this.select.length === 0) {
                    this.$message({ message: '请先选择数据!', type: 'error' })
                } else {
                    this.specialSettleForm = true
                    this.$nextTick(() => {
                        this.$refs.specialSettleForm.dialogForm = true
                        this.$refs.specialSettleForm.list = JSON.parse(JSON.stringify(this.select))
                        this.$refs.specialSettleForm.form.accountUnit = JSON.parse(JSON.stringify(this.select[0].accountUnit))
                        this.$refs.specialSettleForm.loadData()
                    })
                }
            },
            handleDetail(item) {
                getPlanId(item.planId).then(res => {
                    this.dialogForm = true
                    this.$nextTick(() => {
                        this.$refs.specialDetailForm.dialogForm = true
                        let form = JSON.parse(JSON.stringify(res.data))
                        delete form.records
                        this.$refs.specialDetailForm.form = form
                        this.$refs.specialDetailForm.table = res.data.records
                    })
                })
            },
            handleRemove(id) {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deletePlanList(id).then(res => {
                        this.$message({ message: '删除成功!', type: 'success' })
                        this.loadData()
                    })
                })
            },
            handleCancel(item) {
                let data = [{
                    id: item.planId,
                }]
                getSpecialNum(data).then(res => {
                    this.cancelForm = true
                    this.cForm.accountFee = res.data
                    this.cForm.containerId = item.containerId
                    this.cForm.remark = `箱号【${item.containerId}】特殊理箱放行撤销。`
                    this.cForm.id = item.planId
                    this.cForm.accountUnit = item.accountUnit
                    this.cForm.accountWay = item.accountWay
                })
            },
            handleSubmit() {
                cancelSpecial(this.cForm.id, this.cForm).then(res => {
                    this.$message({ message: '撤销成功!', type: 'success' })
                    this.cancelForm = false
                    this.loadData()
                })
            },
            handleChangeEnd(val) {
                let setVal = val;
                if (val) {
                    setVal = val.split(" ")[0] + " 23:59:59";
                }
                this.condition["search_LTE_createDateTime"] = setVal;
            },
            handleSelectionChange(val) {
                this.select = val
            },
            selectable(row, index) {
                return !row.isAccount
            },
            handleExport() {
                let map = new Map();
                map.set("portName", "作业港口")
                map.set("containerId", "箱号")
                map.set("containerSize", "尺寸")
                map.set("containerType", "箱型")
                map.set("tradeType", "内外贸")
                map.set("imOrEx", "进出口")
                map.set("sealNo", "铅封号")
                map.set("finishTime", "完成日期")
                map.set("planType", "作业类型")
                map.set("isAccount", "是否结算")
                map.set("remark", "描述")
                map.set("shipAgentName", "船代")
                map.set("accountUnit", "结算单位")
                map.set("finishUser", "完成人")
                map.set("finishTime", "完成时间")
                map.set("createDateTime", "创建时间")
                if(typeof this.choicePortCode  === 'string'){
                    this.condition.search_IN_portCode = this.choicePortCode
                } else {
                    this.condition.search_IN_portCode = this.arrayToString(this.choicePortCode)
                }
                // this.condition.search_IN_portCode = this.arrayToString(this.choicePortCode)
                let params = this.$assist.copySearchConditions(this.condition)
                params.iDisplayStart = this.pageInfo.pageStart - 1
                params.iDisplayLength = 9999
                params.sortType = '-createDateTime'
                params.search_EQ_type = 'TS'
                getPlanList(params).then(res => {
                    let exportRecords = [];
                    let exportArr = res.data.data.aaData;
                    exportArr.forEach(record => {
                        let exportRecord = {};
                        for (let [key, value] of map.entries()) {
                            if (key === "tradeType") {
                                record[key] = tradeType.get(record[key]);
                            }
                            if (key === "imOrEx") {
                                record[key] = importAndExportType.get(record[key]);
                            }
                            if (key === "isAccount") {
                                record[key] = trueOrFalse.get(record[key]);
                            }
                            if (key === "planType") {
                                record[key] = tsJobStatus.get(record[key]);
                            }
                            if (key === 'finishTime') {
                                record[key] = record[key] ? record[key].substr(0, 10) : '-'
                            }
                            exportRecord[value] = record[key];
                        }
                        exportRecords.push(exportRecord);
                    });
                    newExportExcel("特殊理箱", exportRecords);
                })
            }
        },
        watch: {
            pageInfo: {
                deep: true,
                handler: function () {
                    this.loadData()
                }
            }
        },
        computed: {
            startPickerOptions() {
                let endDate = this.condition["search_LTE_createDateTime"];
                return {
                    disabledDate(time) {
                        if (endDate) {
                            return time.getTime() > new Date(endDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            endPickerOptions() {
                let startDate = this.condition["search_GTE_createDateTime"];
                return {
                    disabledDate(time) {
                        if (startDate) {
                            return time.getTime() < new Date(startDate).getTime();
                        } else {
                            return false;
                        }
                    }
                };
            },
            selectTitle() {
                if (this.select.length === 0) {
                    return '未选择'
                } else {
                    return '已选择 ' + this.select.length + ' 条数据'
                }
            }
        },
        filters: {
            filterDate(val) {
                return val ? val.substr(0, 10) : '-'
            }
        }
    }
</script>

<style scoped>
    .bottom {
        display: flex;
        padding: 0 10px;
        justify-content: space-between;
        align-items: center;
    }

    .operbar {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
    }
</style>
